package com.szy.security.auth.phone;

import com.szy.security.auth.util.SzyAuthenticationUtils;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

/**
 * @author : zhenyun.su
 * @comment : 短信验证身份认证提供者,
 * @since : 2020-9-22
 */
@Deprecated
public class PhoneAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        PhoneAuthenticationToken authenticationToken = (PhoneAuthenticationToken) authentication;

        doAuthentication(authenticationToken);

        //认证管理器循环使用authentication认证数据，在此若认证成功，则新建认证令牌，跳出认证管理器
        PhoneAuthenticationToken result = new PhoneAuthenticationToken(authenticationToken.getPrincipal(), authenticationToken.getAuthorities());
        result.setDetails(authenticationToken.getDetails());
        return result;
    }

    public void doAuthentication(PhoneAuthenticationToken authentication) throws PhoneAuthenticationException {
        PhoneUserDetails phoneUserDetails = (PhoneUserDetails) authentication.getPrincipal();
        String phoneRequest = authentication.getPhone();
        String codeRequest = authentication.getVerificationCode();

        SzyAuthenticationUtils.checkVerificationCode(phoneUserDetails, phoneRequest, codeRequest);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return PhoneAuthenticationToken.class.isAssignableFrom(authentication);
    }

}